#include "Interface.h"
#include <iostream>

// 构造函数
Interface::Interface(const std::string& api_url, const std::string& api_key)
    : communicator_(api_url, api_key) {
  std::cout << "[Interface] Initialized with API URL: " << api_url << std::endl;
}

// 设置上下文数量
void Interface::SetContextSize(size_t context_size) {
  context_size_ = context_size;
  std::cout << "[Interface] Context size set to: " << context_size_
            << std::endl;
}
void Interface::SetMaxTokensSize(size_t max_tokens_size) {
  max_tokens_size_ = max_tokens_size;
}

bool Interface::SetPrompt(const std::string& prompt) {
  if (prompt.empty()) {
    std::cerr << "[Interface] Error: Input cannot be empty." << std::endl;
    return true;
  }

  // 添加用户消息到历史
  message_history_.push_back({"user", prompt});

  // 如果历史消息数量超过上下文数量，移除最早的消息
  if (message_history_.size() > context_size_) {
    message_history_.erase(message_history_.begin());
  }

  // 构建请求
  Request request;
  request.model = "deepseek-r1";
  request.messages = message_history_;  // 使用历史消息
  request.max_tokens = max_tokens_size_;

  // 发送请求并获取响应
  std::cout << "[Interface] Sending request to API..." << std::endl;
  Response response = communicator_.SendRequest(request);

  // 处理响应
  if (response.error) {
    std::cerr << "[Interface] Error: " << response.error_message << std::endl;
  } else if (!response.choices.empty()) {
    std::string ai_response = response.choices[0].content;
    std::cout << "AI: " << ai_response << std::endl;
    if (callback_) {
      callback_(ai_response);
    }
    // 添加 AI 回复到历史
    message_history_.push_back({"assistant", ai_response});
    // 如果历史消息数量超过上下文数量，移除最早的消息
    if (message_history_.size() > context_size_) {
      message_history_.erase(message_history_.begin());
    }
  } else {
    std::cerr << "[Interface] No response from AI." << std::endl;
    }return false;
}void Interface::RegisterCallback(const std::function<void(const std::string& data)>& callback){
    callback_ = callback;
  }